package intermediateCodeClass;

import log4Compile.Log;

import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

/*
    三地址代码基本类
 */
public class MidCode {
    private int size;
    //    private String logFile ="src/main/java/intermediateCodeClass/midCodeFile.txt";
    private LinkedList<MidCodeNode> midCodeNodeLinkedList = new LinkedList<>();
    private static final MidCode midCodeInstance = new MidCode();
    private Log log = Log.getLogInstance();

    private MidCode() {
    }

    public static MidCode getInstance() {
        return midCodeInstance;
    }

    public int getSize() {
        return size;
    }

    public void addNewCode(MidCodeNode midCodeNode) {
        size++;
        midCodeNode.setIndex(size++);
        midCodeNodeLinkedList.add(midCodeNode);
    }

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        for (MidCodeNode midCodeNode : midCodeNodeLinkedList) {
            result.append(midCodeNode.toString()).append("\n");
        }
        return result.toString();
    }

    public String generateCode() {
        StringBuilder result = new StringBuilder();
        for (MidCodeNode midCodeNode : midCodeNodeLinkedList) {
            result.append(midCodeNode.generalCode()).append("\n");
        }
        return result.toString();
    }

    public void writeToFile(String logFile) {
        log.logger("准备将三地址写入文件:" + logFile, 2);
        String midCodeString = generateCode();
        try {
            FileWriter midWrite = new FileWriter(logFile);
            PrintWriter midPrint = new PrintWriter(midWrite);
            midPrint.print(midCodeString);
            midPrint.close();
            midWrite.close();
            System.out.println("格式化的三地址代码已写入文件");
            log.logger("格式化的三地址代码已写入文件", 2);
        } catch (FileNotFoundException ex) {
            System.out.println("File Not Found !");
            log.logger("文件未找到", 2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void clean() {
        midCodeNodeLinkedList.clear();
    }
}
